/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MainClasses;

import MainClasses.EventListeners.*;
import GUIComponents.*;

import GUIComponents.Menu.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
 *
 * @author andrewcutler
 */
public class main {
    
    private static JFrame loadingScreen;
    private static JFrame mainScreen;
    private static JFrame assignmentFrame;
    private static JFrame eventFrame;
    
    private static HWTabbedPane tabbedPane;
    private static boolean error;
    private static Preferences prefs;
    private static CourseManager courseManager;
    private static Course userCourse;
    
    private static WebHandler web;
    
    private static int dateOffset;
    
    
    
    //initializes stuff
    public static void main(String[] args)
    {        
        initLoadingScreen();
        showLoadingScreen();
        
        dateOffset = 0;
        assignmentFrame = null;
        
        createCourseManager();
        
        if(!loadPrefs())
        {
            showFirstRun();
        }
        else
        {
            runMain();
        }
    }
    
    private static void runMain()
    {
        if(fetchData())
        {            
        }
        else
        {
            
            disposeMainScreen();
            mainScreen = new JFrame("Error");
            mainScreen.add(new JLabel("There was an error connecting to HHMS. Please connect to the internet and try again.     "));
            mainScreen.addWindowListener(new ExitListener());
            mainScreen.pack();
            hideLoadingScreen();
            showMainScreen();
            try {
                Thread.sleep(1000);                
            }
            catch(Exception e)            {
                
            }
            //error = true;
        }
        
        if(!error)
        {
            parseData();
            initUserCourse();
            initGUI();
            
            courseManager.loadAll(prefs);
            resetTabbedPane();
            //mainScreen.setSize(1000,700);
            //try{ Thread.sleep(1000);} catch(Exception e){System.out.println(e);}
            hideLoadingScreen();
            showMainScreen();
        }
        
    }
    
    //Initializes the Loading Screen
    private static void initLoadingScreen()    {
        disposeLoadingScreen();
        loadingScreen = new JFrame("Loading...");
        JProgressBar progressBar = new JProgressBar();
        loadingScreen.setResizable(false);
        center(loadingScreen);
        loadingScreen.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        loadingScreen.setLayout(new GridLayout(1,1));
        loadingScreen.add(progressBar);
        progressBar.setIndeterminate(true);
        
        loadingScreen.setSize(400,25);
    }
    
    private static JProgressBar initFetchingLoadingScreen(){
        disposeLoadingScreen();
        loadingScreen = new JFrame("Fetching Data from HHMS...");
        loadingScreen.setResizable(false);
        loadingScreen.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        loadingScreen.setLayout(new GridLayout(1,1));
        center(loadingScreen);
        JProgressBar progressBar = new JProgressBar();
        progressBar.setIndeterminate(false);
        progressBar.setStringPainted(true);
        progressBar.setValue(0);
        //loadingScreen.pack();
        loadingScreen.setSize(400,55);
        loadingScreen.validate();
        return progressBar;
    }
    public static void  initAddEventFrame(){
        eventFrame = new AddEventFrame();
        eventFrame.setVisible(true);
    }
    
    public static void initDeleteEventFrame(){
        eventFrame = new DeleteEventFrame();
        eventFrame.setVisible(true);
    }
    
    public static void listEvents() {
        eventFrame = new ListEventFrame();
        eventFrame.setVisible(true);
    }
    
    private static void showLoadingScreen()    { loadingScreen.setVisible(true);  }
    private static void hideLoadingScreen()    { loadingScreen.setVisible(false); }
    private static void showMainScreen()       { mainScreen.setVisible(true);     }
    private static void hideMainScreen()       { mainScreen.setVisible(false);    }
    
    private static void disposeLoadingScreen()    {
        
        if(loadingScreen != null){
            loadingScreen.removeAll();
            loadingScreen.dispose();
        }
    }
    private static void disposeMainScreen()    {
        if(mainScreen != null)
            mainScreen.dispose();
    }
    public  static void disposeEventFrame() {
        if(eventFrame != null)
            eventFrame.dispose();
    }
    
    private static boolean loadPrefs()    {
        prefs = new Preferences(courseManager);
        return prefs.loadPreferences();
    }
    
    private static void createCourseManager()    {
        courseManager = new CourseManager();
    }
    
    public  static CourseManager getCourseManager() {return courseManager;}
    
    private static void initUserCourse() {
        userCourse = new Course();
        userCourse.setCourseName("User Events");
        userCourse.setId(prefs.getID());
        userCourse.setPeriod(500);
        userCourse.setTeacher(prefs.getStudentName());
        courseManager.addCourse(userCourse);
    }
    
    public static Course getUserCourse()
    {
        return userCourse;
    }
    
    public static void updateAssignments()
    {
        initLoadingScreen();
        showLoadingScreen();
        courseManager.purge();
        fetchData();
        initLoadingScreen();
        showLoadingScreen();
        parseData();
        resetTabbedPane();
        disposeLoadingScreen();
    }
        
    private static boolean fetchData()    {
        JProgressBar bar = initFetchingLoadingScreen();
        showLoadingScreen();
        
        for(int i = 0; i<4; i++)
        {
            bar.setString("Fetching week " + (i + 1) + "...");
            loadingScreen.setTitle("Fetching week " + (i+1) + "...");
            web = new WebHandler(prefs, i);
            bar.setValue(i*25);
        }
        return !web.connectionFailed();
    }
    private static void parseData()    {
        for(int i = 0; i<4; i++)
        {
            XMLParser.parse(prefs, courseManager, i);
        }
        
    }
    
    private static void initGUI()    {
        disposeMainScreen();
        mainScreen = new JFrame("HomeworkManager");
        mainScreen.addWindowListener(new ExitListener());
        JMenuBar menuBar = new JMenuBar();
        addMenus(menuBar);
        
        mainScreen.setJMenuBar(menuBar);
        
        tabbedPane = new HWTabbedPane(courseManager);
        mainScreen.add(tabbedPane);
        
        
        
        //mainScreen.pack();
        
        maximize(mainScreen);
    }
    
    private static void showFirstRun(){
        disposeMainScreen();
        
        mainScreen = new JFrame("Setup HomeworkManager");
        mainScreen.addWindowListener(new ExitListener());
        Container content = mainScreen.getContentPane();
        
        content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
        
        JLabel errorLabel = new JLabel("  ");
        JTextField idField = new JTextField();
        JTextField emailField = new JTextField();
        
        JButton idButton = new JButton("Set Student ID [Required]");
        idButton.setActionCommand(SetupScreenListener.SET_ID);
        idButton.addActionListener(new SetupScreenListener(idField));
        
        
        JButton emailButton = new JButton("Set Email [Not Required]");
        emailButton.setActionCommand(SetupScreenListener.SET_EMAIL);
        emailButton.addActionListener(new SetupScreenListener(emailField));
        
        JButton exitButton = new JButton("Done");
        exitButton.addActionListener(new DoneButtonListener());
        
        content.add(idField);
        content.add(idButton);
        content.add(emailField);
        content.add(emailButton);
        content.add(errorLabel);
        content.add(exitButton);
        
                
        mainScreen.pack();
        center(mainScreen);
        mainScreen.setSize(300,175);
        hideLoadingScreen();
        showMainScreen();
    }
    
    private static void addMenus(JMenuBar menuBar)
    {
        addFileMenu(menuBar);
        addDayMenu(menuBar);
        addModeMenu(menuBar);
        addEventMenu(menuBar);
    }
    private static void addFileMenu(JMenuBar menuBar){
        JMenu fileMenu = new FileMenu();
        menuBar.add(fileMenu);
    }
    private static void addDayMenu(JMenuBar menuBar){
        JMenu dayMenu = new DayMenu();        
        menuBar.add(dayMenu);
    }
    private static void addModeMenu(JMenuBar menuBar){
        JMenu modeMenu = new ModeMenu();
        menuBar.add(modeMenu);
    }
    private static void addEventMenu(JMenuBar menuBar){
        JMenu eventMenu = new EventMenu();
        menuBar.add(eventMenu);
    }
    
    
    public static Preferences getPrefs()                 { return prefs;                          }
    public static WebHandler getWeb()                    { return web;                            }
            
    public static JFrame getAssignmentFrame()            { return assignmentFrame;                }
    public static void setAssignmentFrame(JFrame frame)  { assignmentFrame = frame;               }
    
    public static MyDate getCurrentDate(int i)           { return MyDate.getDate(dateOffset + i); }
    public static MyDate getCurrentDate()                { return MyDate.getDate(dateOffset);     }
    
    public static int getOffset()                        { return dateOffset;                     }
    public static void setOffset(int i)                  { dateOffset = i;                        }
    public static void addOffset(int i)                  { dateOffset += i;                       }
    
    public static void resetTabbedPane()                 { tabbedPane.reset(); }
    public static HWTabbedPane getTabbedPane()                  { return tabbedPane;  }
    
    
    
    public static void exit(int i){
        prefs.savePreferences();
        courseManager.saveChecks(prefs);
        courseManager.saveEvents(prefs);
        //error("Error: " + error);
        System.exit(i);
    }
    
    
    
    public static void error(String s)      { tabbedPane.getDebugPanel().println("ERR ERROR: " + s); }
    public static void error(Object o)      { if(o!=null){tabbedPane.getDebugPanel().println("ERR ERROR: " + o); } }
    public static void println(String s)    { tabbedPane.getDebugPanel().println(s); }
    public static void println(int i)       { tabbedPane.getDebugPanel().println(i); }
    public static void println(boolean b)   { tabbedPane.getDebugPanel().println(b); }
    public static void println(Object o)    { tabbedPane.getDebugPanel().println(o); }
    
    
    
    public static void center(JFrame frame) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        Point center = ge.getCenterPoint();
        Rectangle bounds = ge.getMaximumWindowBounds();
        int w = Math.max(bounds.width/2, Math.min(frame.getWidth(), bounds.width));
        int h = Math.max(bounds.height/2, Math.min(frame.getHeight(), bounds.height));
        int x = center.x - w/2, y = center.y - h/2;
        frame.setBounds(x, y, w, h);
        if (w == bounds.width && h == bounds.height)
            frame.setExtendedState(Frame.MAXIMIZED_BOTH);
        frame.validate();
    }
    
    public static void maximize(JFrame frame){
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        Rectangle max = ge.getMaximumWindowBounds();
        frame.setBounds(max);
        
        //frame.validate();
    }
    
    private static class ExitListener extends WindowAdapter implements ActionListener {
        @Override
        public void windowClosing(WindowEvent e)        {
            main.exit(0);
        }

        public void actionPerformed(ActionEvent arg0) {
            main.exit(0);
        }
    
    }
    
    private static class DoneButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent evt)        {
            initLoadingScreen();
            showLoadingScreen();
            hideMainScreen();
            prefs.savePreferences();
            runMain();
        }
    }
    
    public static void hellaCalendarStuff(){
        // get the supported ids for GMT-08:00 (Pacific Standard Time)
 String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
 // if no ids were returned, something is wrong. get out.
 if (ids.length == 0)
     System.exit(0);

  // begin output
 System.out.println("Current Time");

 // create a Pacific Standard Time time zone
 SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);

 // set up rules for daylight savings time
 pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
 pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);

 // create a GregorianCalendar with the Pacific Daylight time zone
 // and the current date and time
 Calendar calendar = new GregorianCalendar(pdt);
 Date trialTime = new Date();
 calendar.setTime(trialTime);

 // print out a bunch of interesting things
 System.out.println("ERA: " + calendar.get(Calendar.ERA));
 System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
 System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
 System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
 System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
 System.out.println("DATE: " + calendar.get(Calendar.DATE));
 System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
 System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
 System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
 System.out.println("DAY_OF_WEEK_IN_MONTH: "
                    + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
 System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
 System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
 System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
 System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
 System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
 System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
 System.out.println("ZONE_OFFSET: "
                    + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000)));
 System.out.println("DST_OFFSET: "
                    + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000)));

 System.out.println("Current Time, with hour reset to 3");
 calendar.clear(Calendar.HOUR_OF_DAY); // so doesn't override
 calendar.set(Calendar.HOUR, 3);
 System.out.println("ERA: " + calendar.get(Calendar.ERA));
 System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
 System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
 System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
 System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
 System.out.println("DATE: " + calendar.get(Calendar.DATE));
 System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
 System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
 System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
 System.out.println("DAY_OF_WEEK_IN_MONTH: "
                    + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
 System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
 System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
 System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
 System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
 System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
 System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
 System.out.println("ZONE_OFFSET: "
        + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); // in hours
 System.out.println("DST_OFFSET: "
        + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); // in hours
    }
    

}
